import React, { useMemo } from 'react'
import { Button } from 'antd'
import type { ButtonProps } from 'antd'
import { useSelector } from 'react-redux'
import type { RootState } from '../store'

type Props = ButtonProps & { perKey: string }

const PermissionButton: React.FC<Props> = ({ children, perKey, ...ButtonProps }) => {
  const permission = useSelector((state: RootState) => state.user.userInfo?.permission || [])
  // 根据传入权限key值去当前用户的权限列表中查找
  const isPer = useMemo(() => {
    return !!permission.find(v => v.path === perKey)
  }, [permission, perKey])
  // 存在此权限就显示按钮
  if (isPer) {
    return <Button {...ButtonProps}>{children}</Button>
  }
  return null
}

export default PermissionButton